package com.nova.bluetooth.base;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.ViewDataBinding;

import com.nova.bluetooth.helpUtils.ActivityCollector;
import com.nova.bluetooth.helpUtils.LogUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import me.jessyan.autosize.AutoSizeCompat;

public class BaseActivity extends AppCompatActivity {
    protected String TAG = getClass().getSimpleName();
    protected ViewDataBinding mBinding;
    /**
     * 将密度独立像素值（dp）转换为像素值（px）
     *
     * @param context 上下文
     * @param dp      密度独立像素值
     * @return 像素值（px）
     */
    public static int dpToPx(Context context, float dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX, dp, context.getResources().getDisplayMetrics());
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtil.d("当前Activity：" + TAG);

        //在活动管理器添加当前Activity
        ActivityCollector.addActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBinding != null) {
            mBinding.unbind();
            mBinding = null;
        }
        //从活动管理器删除当前Activity
        ActivityCollector.removeActivity(this);
    }

    /**
     * 设置 app 字体不随系统字体设置改变
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        if (res != null) {
            runOnUiThread(() -> {
                //防止三星等部分手机界面重建时，界面显示异常
                AutoSizeCompat.autoConvertDensityOfGlobal(res); //如果没有自定义需求用这个方法
            });
        }
        return res;
    }


    public void setPaddingBottom2(Activity activity, View view) {
        activity.getWindow().getDecorView().post(() -> {
            WindowManager manager =
                    (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
            int decorViewHeight = activity.getWindow().getDecorView().getHeight();
            DisplayMetrics dm = new DisplayMetrics();
            manager.getDefaultDisplay().getMetrics(dm);
            int useableScreenHeight = dm.heightPixels;
            int statusBarHeight = getStatusBarHeight(activity);
            boolean hasNavigation = decorViewHeight != useableScreenHeight + statusBarHeight;
            if (hasNavigation) {
                view.setPadding(view.getPaddingLeft(), view.getPaddingTop(),
                        view.getPaddingRight(), getNavigationHeight(activity));
            }
        });
    }

    /**
     * 底部有导航栏时，防止导航栏遮挡处理
     * @param activity
     * @param view
     */
    public void setPaddingBottom(Activity activity, View view) {
        int nHeight = getNavigationHeight(activity);

        //结合两个判断才能更精确判断出是否有导航栏
        if (checkDeviceHasNavigationBar(activity) && nHeight > 65) {
            view.setPadding(view.getPaddingLeft(), view.getPaddingTop(), view.getPaddingRight(), nHeight);
        }
    }

    private static int getNavigationHeight(Context activity) {
        if (activity == null) {
            return 0;
        }
        Resources resources = activity.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height",
                "dimen", "android");
        int height = 0;
        if (resourceId > 0) {
            //获取NavigationBar的高度
            height = resources.getDimensionPixelSize(resourceId);
        }
        return height;
    }

    private static boolean checkDeviceHasNavigationBar(Context context) {
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display defaultDisplay = manager.getDefaultDisplay();
        //屏幕实际高度
        Point realPoint = new Point();
        defaultDisplay.getRealSize(realPoint);
        //屏幕显示高度
        DisplayMetrics outMetrics = new DisplayMetrics();
        defaultDisplay.getMetrics(outMetrics);
        //虚拟底部导航高度
        int navigationBarHeight = getNavigationHeight(context);
        if ((outMetrics.heightPixels + navigationBarHeight) <= realPoint.y) {
            //如果显示高度+底部导航栏高度 <= 屏幕真实高度， 说明显示虚拟底部导航栏，反之则不显示
            return true;
        }
        return false;

    }

    public static int getStatusBarHeight(Context context) {
        Resources resources = context.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            return resources.getDimensionPixelSize(resourceId);
        }
        return 0;
    }


    protected boolean isDateBeforeCurrentDate(String inputDateString) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        try {
            Date inputDate = dateFormat.parse(inputDateString);

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(inputDate);
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);

            Calendar currentDate = Calendar.getInstance();
            currentDate.set(Calendar.HOUR_OF_DAY, 0);
            currentDate.set(Calendar.MINUTE, 0);
            currentDate.set(Calendar.SECOND, 0);
            currentDate.set(Calendar.MILLISECOND, 0);

            return calendar.before(currentDate);
        } catch (ParseException e) {
            Log.e("MainActivity", "Error parsing date: " + e.getMessage());
            return false; // 或者根据需要抛出异常
        }
    }
}
